package com.gc.common.shiro.realm;

import com.gc.pojo.SysUser;
import com.gc.common.shiro.services.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysLoginService loginService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        //给用户授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("*:*:*");
//        //拿到当前用户对象
        Subject subject = SecurityUtils.getSubject();
        SysUser currentUser = (SysUser) subject.getPrincipal();  //拿到user对象
        Set<String> keys = loginService.getUserRoleKeyByUid(currentUser.getUserId());  //获取权限编号
        info.setRoles(keys);
//        Set<String> permissions  = loginService.getUserAuthsByUid(currentUser.getUserId());
//////        info.setStringPermissions(permissions);
        //授权
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String loginName = upToken.getUsername();
        String password = "";
        if (upToken.getPassword() != null) {
            password = new String(upToken.getPassword());
        }
        SysUser user = loginService.login(loginName, password);
        if(user == null){
            return null;  //自动抛出 , UnknownAccountException
        }
        if(!user.getPassword().equals(password)){
            throw new IncorrectCredentialsException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password,"");
        return info;
    }
}
